Ext.define('Admin.view.sys.dic.MainViewController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.sys_dic_mainviewcontroller',

    listen: {
        component: {
            'sys_dictype_sysdictypetree': {
                //左树单击事件
                itemclick: 'handlerTypeTreeItemclick'
            },

            'sys_dic_treegridlist': {
                //树加载完成时间
                storeload: 'handleTreeGridStoreload'
            }
        }
    },

    /*左树单击事件*/
    handlerTypeTreeItemclick: function (tree, record, item, index, e, eOpts) {
        if (record.get('id') !== '0' && record.isLeaf()) {
            var param = {};
            //获取左树(字典类型)选中节点ID
            param.sysDicTypeId = record.getId();
            //获取当前树组件
            var grid = this.lookup('treeGrid');
            //设置根节点文本
            grid.getRootNode().set('text', record.get('text'));
            grid.getRootNode().commit();
            //加载当前树组件
            grid.getStore().proxy.extraParams = param;
            grid.refreshView();
        }
    },

    /*加载完成展开树*/
    handleTreeGridStoreload: function (store, node, records, successful, eOpts) {
        this.lookup('treeGrid').getSelectionModel().select(0);
        this.lookup('treeGrid').getRootNode().expand();
    },

    /*新增菜单节点*/
    onAdd: function () {

        var leftTreeGrid = this.lookup('leftTreeGrid');
        var leftRecord = leftTreeGrid.getSelecedRecord();
        var leftTreeId = leftTreeGrid.getSelectedRecordId();

        if (leftTreeId === '0' || !leftTreeId) {
            Ext.popup.Msg('提示信息', '请先选择字典类别(左树)');
            return;
        }
        if (!leftRecord.isLeaf()) {
            Ext.popup.Msg('提示信息', '字典类别不可以选择根节点');
            return;
        }

        //字典类型编码
        var sysDicTypeCode = leftRecord.get('code');
        //字典形式(combo|tree)
        var type = leftRecord.get('type');

        if (!this.addValidate()) {
            Ext.popup.Msg('提示信息', '请选择一个节点');
            return;
        }

        var me = this,
            treeGrid = me.lookup('treeGrid'),
            cellEditingPlugin = treeGrid.cellEditingPlugin,
            selectionModel = treeGrid.getSelectionModel(),
            //selectedList = selectionModel.getSelection()[0],
            selectedList = type === 'combo' ? treeGrid.getRootNode() : selectionModel.getSelection()[0],
            newList = Ext.create('Admin.model.sys.dic.SysDicModel', {
                text: '输入类别名称',
                loaded: true,
                leaf: true,
                sysDicTypeId: leftTreeId,
                sysDicTypeCode: sysDicTypeCode,
                code: ''
            }),
            expandAndEdit = function () {
                selectionModel.select(newList);
                me.addedNode = newList;
                cellEditingPlugin.startEdit(newList, 0);
            };
        if (selectedList.isLeaf()) {
            selectedList.set('leaf', false);
            selectedList.set('loaded', true);
        }
        selectedList.expand();
        selectedList.appendChild(newList);
        newList.phantom = false;
        if (treeGrid.getView().isVisible(true)) {
            expandAndEdit();
        } else {
            treeGrid.on('expand', function onExpand() {
                expandAndEdit();
                treeGrid.un('expand', onExpand);
            });
            treeGrid.expand();
        }
    },

    /**
     * 添加机构节点前验证是否选择了根节点
     */
    addValidate: function () {
        return this.lookup('treeGrid').getSelectedRecordId() ? true : false;
    },

    /*编辑节点*/
    onEdit: function (grid, rowIndex, colIndex, item, e, record, row) {
        var me = this;
        if (record.getId() === '0') {
            Ext.popup.Msg('提示信息', '根节点不允许编辑');
            return;
        }
        var treeGrid = me.lookup('treeGrid');
        var cellEditingPlugin = treeGrid.cellEditingPlugin;
        cellEditingPlugin.startEdit(record, 0);
    },

    /* 保存新增或修改的数据 */
    onSave: function () {
        var me = this;
        if (me.lookup('treeGrid').getModifiedRecordSize() <= 0) {
            Ext.popup.Msg('提示信息', '没有修改过的数据');
            return;
        }
        Ext.Msg.show({
            title: '提示信息',
            msg: '确定该操作吗?',
            buttons: Ext.Msg.OKCANCEL,
            icon: Ext.Msg.QUESTION,
            fn: me.doSaveRecord,
            scope: me
        });
    },
    doSaveRecord: function (buttonId) {
        if (buttonId === "ok") {
            var me = this;
            var treeGrid = me.lookup('treeGrid');
            me.getView().setLoading('数据保存中...');
            treeGrid.getStore().sync({
                success: function () {
                    Ext.popup.Msg('提示信息', '保存成功');
                },
                callback: function () {
                    me.getView().setLoading(false);
                    treeGrid.refreshView();
                }
            });
        }
    },

    /*删除节点*/
    onDelete: function (grid, rowIndex, colIndex, item, e, record, row) {
        var me = this;

        if (record.getId() === '0') {
            Ext.popup.Msg('提示信息', '根节点不允许删除');
            return;
        }

        Ext.Msg.show({
            title: '提示信息',
            msg: '确定该操作吗?',
            buttons: Ext.Msg.OKCANCEL,
            icon: Ext.Msg.QUESTION,
            fn: function (buttonId) {
                if (buttonId === "ok") {
                    var treeGrid = this.lookup('treeGrid');
                    var removeNodes = [];

                    //递归子节点
                    record.cascadeBy(function (n) {
                        removeNodes.push(n);
                    });

                    //循环从把model对象删除,这样ext的store会感知到数据变化
                    Ext.Array.each(removeNodes, function (n) {
                        n.remove();
                    }, this, true);

                    //同步数据到服务器,会把删除的数据发送到服务器
                    me.getView().setLoading('数据删除中...');
                    treeGrid.getStore().sync({
                        success: function () {
                            Ext.popup.Msg('提示信息', '删除成功');
                        },
                        callback: function () {
                            me.getView().setLoading(false);
                            treeGrid.refreshView();
                        }
                    });
                }
            },
            scope: me
        });
    },

    /*禁用 启动节点*/
    onStop: function (grid, rowIndex, colIndex, item, e, record, row) {
        var me = this;

        if (record.getId() === '0') {
            Ext.popup.Msg('提示信息', '根节点不允许操作');
            return;
        }

        Ext.Msg.show({
            title: '提示信息',
            msg: '确定该操作吗?',
            buttons: Ext.Msg.OKCANCEL,
            icon: Ext.Msg.QUESTION,
            fn: function (buttonId) {
                if (buttonId === "ok") {
                    Ext.Ajax.request({
                        url: ServerUrl + '/SysDicController/stopById',
                        successHint: true,
                        maskContainer: me.getView(),
                        params: {
                            id: record.getId()
                        },
                        success: function () {
                            me.onRefresh();
                        }
                    });
                }
            },
            scope: me
        });
    },

    /*服务器重新加载菜单数据*/
    onRefresh: function () {
        this.lookup('treeGrid').refreshView();
    }
});
